﻿<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>ajax</title>
		<style>
			*{
				margin:0;
				padding:0;
			}
			ul,li{
				list-style:none;
			}
			#list{
				width:500px;
				height:300px;
				margin:300px auto;
				position:relative;
			}
			#txt{
				width:300px;
				height:50px;
			}
			ul{
				position:absolute;
				top:50px;
				left:0;
				display:block;
				border:1px solid #ccc;
				width:300px;
			}
			.active{
				background:blue;
				cursor:pointer;
			}
		</style>
	</head>
	<body>
		<div id="list">
			<input id="txt" type="text"></input>
			<button>点击搜索</button>
			<ul>
			
			</ul>
		</div>
		
	</body>
	<script type="text/javascript">
		var txt=document.getElementById("txt");
		var oUl=document.getElementById("list").children[2];
		var lilist=[];
		var j=-1;
		txt.onkeypress=function(e){
			var e=e || event;
			//创建参数
			var req=new XMLHttpRequest();
			//设置参数
			req.open("get","http://10.9.163.6/h51642/day23/suggest.php?kw="+this.value,true)
			//事件函数
			req.onreadystatechange=function(){
				if(req.readyState==4){
					var res=req.responseText.substring(0,req.responseText.length-1);
					var arr=res.split(",");
					oUl.innerHTML="";
					arr.forEach(function(item,index,array){
						var li=document.createElement("li");
						oUl.appendChild(li);
						li.innerHTML=item;
					});
					oUl.style.display="block";
					//给一个li设置点击事件
					lilist=oUl.children;
					for(var i=0;i<lilist.length;i++){
						//lilist[i].index=i;
						lilist[i].onclick=function(){
							txt.value=this.innerHTML;
							oUl.style.display="none";
						}
						lilist[i].onmouseover=function(){
							for(var i=0;i<lilist.length;i++){
								lilist[i].className="";
							}
							this.className="active";
						}
					}
					//键盘
					if(e.keyCode==40 || e.keyCode==38 || e.keyCode==13){
						//下键
						if(e.keyCode==40){
							j++;
							j>=lilist.length?j=0:"";
						}
						//上键
						if(e.keyCode==38){
							j--;
							j<0?j=lilist.length-1:"";
						}
						for(var i=0;i<lilist.length;i++){
							lilist[i].className="";
						}
						lilist[j].className="active";
						//回车键
						if(e.keyCode==13){
							txt.value=lilist[j].innerHTML;
							oUl.style.display="none";
						}
						
					}
				}
			}
			//发送
			req.send();
			
		}
	</script>
</html>